其他
Android 现在还能执行后台任务吗?试试 WorkManager 吧
https://www.jianshu.com/u/3994846b6c55
请注意,执行可能会被推迟,因为受到Constraints下设置的电池优化、息屏、网络等模式影响。
implementation "android.arch.work:work-runtime:1.0.1"
implementation "android.arch.work:work-firebase:1.0.0-alpha11"
override fun doWork(): Result {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
WorkManager.getInstance().enqueue(baseWork)
override fun doWork(): Result {
Log.i("MainWorker","点击${inputData.getString("LiveDataTest")}")
val data = Data.Builder().putString("LiveDataTest","LiveDataTest修改后的信息---").build()
return Result.success(data)
}
}
var data = Data.Builder().putString("LiveDataTest","有生命的数据监听··").build()
//2 构建work
val liveDataWork = OneTimeWorkRequest.Builder(BtnTwoWorker::class.java).setInputData(data).build()
//3 通过work的id获取Status
val status = WorkManager.getInstance().getWorkInfoByIdLiveData(liveDataWork.id)
//4 监听状态以及数据的变化
//注意一点:这里的监听的时候 状态改变Observer就会跑一遍~~
status.observe(this, Observer {
if(it.state == WorkInfo.State.SUCCEEDED){
mViewModel.data.value = it.outputData.getString("LiveDataTest")
Log.i("WorkerActivity", it.outputData.getString("LiveDataTest")?:"空")
}
Log.i("WorkerActivity",it.state.name)
Log.i("WorkerActivity","${it.state.isFinished}")
})
//再放入到WorkManager的队列中
WorkManager.getInstance().enqueue(liveDataWork)
/////////////////////////////////////////////////////
2019-10-14 16:54:33.951 15770-15770/testview.zhen.com.myapplication I/WorkerActivity: ENQUEUED
2019-10-14 16:54:33.951 15770-15770/testview.zhen.com.myapplication I/WorkerActivity: false
2019-10-14 16:54:33.972 15770-15849/testview.zhen.com.myapplication I/MainWorker: 点击有生命的数据监听··
2019-10-14 16:54:33.975 15770-15800/testview.zhen.com.myapplication I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=fa81ea63-6c23-4d40-a72f-7f0eea3baf91, tags={ testview.zhen.com.myapplication.jetpack.BtnTwoWorker } ]
2019-10-14 16:54:34.000 15770-15770/testview.zhen.com.myapplication I/WorkerActivity: LiveDataTest修改后的信息---
2019-10-14 16:54:34.000 15770-15770/testview.zhen.com.myapplication I/WorkerActivity: SUCCEEDED
2019-10-14 16:54:34.000 15770-15770/testview.zhen.com.myapplication I/WorkerActivity: true
* Returns {@code true} if this State is considered finished.
*
* @return {@code true} for {@link #SUCCEEDED}, {@link #FAILED}, and
* {@link #CANCELLED}
* states
*/
public boolean isFinished() {
return (this == SUCCEEDED || this == FAILED || this == CANCELLED);
}
setRequiresBatteryNotLow:是否为低电量时运行 setRequiredNetworkType:网络连接设置 setRequiresCharging:是否在充电情况下运行 setRequiresDeviceIdle:设备是否为空闲 setRequiresStorageNotLow:设备可用存储是否不低于临界阈值
override fun doWork(): Result {
Log.i("MainWorker","点击${inputData.getString("delayWork")} --所在线程 ${Thread.currentThread().name}")
val time = inputData.getString("time")
val data = Data.Builder().putString("LiveDataTest","LiveDataTest修改后的信息---").build()
return Result.success(data)
}
}
val constrains = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
//2 构建 Data数据
var data = Data.Builder().putString("delayWork","延时操作~~~").putInt("time",10).build()
//3 构建workRequest
val workConstrains = OneTimeWorkRequest.Builder(DelayWorker::class.java)
.setConstraints(constrains)
.setInputData(data)
.build()
//4 获取Status监听数据
val status = WorkManager.getInstance().getWorkInfoByIdLiveData(workConstrains.id)
status.observe(this, Observer {
Log.i("WorkerActivity",it?.state?.name)
if (it?.state!!.isFinished) {
Log.e("TestWorker", "Finish")
}
})
//5 添加到equque
WorkManager.getInstance().enqueue(workConstrains)
////////////////////////////////////////////////////////////////////////////////////
2019-10-14 17:57:28.140 25296-25296/testview.zhen.com.myapplication I/WorkerActivity: ENQUEUED 【------没有连接网络的时候先等待】
2019-10-14 17:57:36.609 25296-25296/testview.zhen.com.myapplication I/WorkerActivity: RUNNING 【------有网络的时候执行】
2019-10-14 17:57:36.610 25296-25469/testview.zhen.com.myapplication I/MainWorker: 点击延时操作~~~ --所在线程 pool-1-thread-1
2019-10-14 17:57:36.613 25296-25325/testview.zhen.com.myapplication I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=fc71f417-8289-4f8c-a489-4d8699960f3d, tags={ testview.zhen.com.myapplication.jetpack.DelayWorker } ]
2019-10-14 17:57:36.637 25296-25296/testview.zhen.com.myapplication I/WorkerActivity: SUCCEEDED
WorkManager.getInstance().cancelWorkById(workConstrains.id)
//取消任务 方式2: (这个方式我取消了但是不知道为什么任务都不会停止)
//这里传入的参数 true 如果线程执行, 任务应该被打断 false,允许在进行任务, 完成;
//WorkManager.getInstance().getWorkInfoById(workConstrains.id).cancel(true)
/** 通过在WorkRequestBuilder 设置 TAG 然后获取TAG进行取消任务 **/
OneTimeWorkRequest.Builder(BtnTwoWorker::class.java)
.addTag("TAG")
.setInputData(data)
.build()
//取消任务 方式2:
WorkManager.getInstance().getStatusesByTag("TAG")
//取消任务 具有特定标记的所有任务 **TAG可以相同**
WorkManager.getInstance().cancelAllWorkByTag("TAG")
WorkRequest request2 = new OneTimeWorkRequest.Builder(BarWorker.class).build();
WorkRequest request3 = new OneTimeWorkRequest.Builder(BazWorker.class).build();
workManager.beginWith(request1, request2).then(request3).enqueue();
continuation.then(B).then(D, E).enqueue(); // A is implicitly enqueued here
continuation.then(C).enqueue();
.beginUniqueWork("onlyOne", ExistingWorkPolicy.KEEP, work)
.enqueue()
REPLACE:如果有现有的等待(未完成)使用相同的惟一名称,取消和删除它。然后插入现有的任务。 KEEP:如果有现有的等待(未完成)使用相同的惟一名称,则什么也不做。否则,插入现有的任务。 APPEND:如果有现有的等待(未完成)使用相同的惟一名称附加的, 新指定的工作作为一个孩子的所有的叶子工作序列。否则,插入现有的任务开始一个新的序列。